const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onError = require('koa-onerror');
const bodyParser = require('koa-bodyparser');
const logger = require('koa-logger');

const index = require('./controllers/index');

// error handler
onError(app);

// middleware
app.use(bodyParser({
  enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

app.use(views(__dirname + '/views', {
  extension: 'pug'
}));

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

/** middleware 中间件 */
let middleware = require('./middlewares/index');
/** 公共函数 （污染全局的做法，但是这样很方便）*/
app.use(middleware.common());
/** 权限验证 */
app.use(middleware.author());
/** 错误处理*/
app.use(middleware.errorHandle());
/** controllers 路由加载*/
app.use(index.routes(), index.allowedMethods());
module.exports = app;
